
var map;
var mapCenter;
var marker;
//todo change from agents markers to agents with name and id and stuff
var agentMarkers;
if (!agentMarkers) {
    agentMarkers = new Array();
}
var deathCount=0;
var totalEnemies;

function reattachMap() {
    var myOptions = {
      zoom: 17,
      center: mapCenter,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var mapDiv = $("#map").get(0);
    map = new google.maps.Map(mapDiv, myOptions);
    
    marker = new google.maps.Marker({position: mapCenter, icon: 'images/me.png'});
    marker.setMap(map);
    
    if (agentMarkers) {
        for (var i=0; i<agentMarkers.length; i++) {
            agentMarkers[i][1].setMap(map);
            agentMarkers[i][2].setMap(map);
        }
    }
}

function mapGoogle(latitude,longitude) {
    mapCenter = new google.maps.LatLng(latitude,longitude);
    reattachMap();
}

function getPhonePosition() {
    var ret;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( 
            // Success function
            function (position) {  
                var mapCenter = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                marker.setPosition(mapCenter)
            },
            // Failure function 
            function (error) {
                switch(error.code) {
                    case error.TIMEOUT:
                        break;
                    case error.POSITION_UNAVAILABLE:
                        break;
                    case error.PERMISSION_DENIED:
                        break;
                    case error.UNKNOWN_ERROR:
                        break;
                }
            }
        );
    }
    return ret;
}

function mapInit() {
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition( 

    function (position) {  

        // Did we get the position correctly?
        // alert (position.coords.latitude);

        // To see everything available in the position.coords array:
        // for (key in position.coords) {alert(key)}

        mapGoogle(position.coords.latitude,position.coords.longitude);
        }, 
        // next function is the error callback
        function (error)
        {
        switch(error.code) 
        {
        case error.TIMEOUT:
        break;
        case error.POSITION_UNAVAILABLE:
        break;
        case error.PERMISSION_DENIED:
        break;
        case error.UNKNOWN_ERROR:
        break;
        }
        }
        );
    }
}

function updateMarker(markerIndex, loc) {
    var agentloc= new google.maps.LatLng(loc[0], loc[1]);
    var iconLoc = (loc[3]) ? 'images/agent.png' : 'images/dead.png';
    
    agentMarkers[markerIndex][1].setPosition(agentloc);
    agentMarkers[markerIndex][1].setIcon(iconLoc);
    agentMarkers[markerIndex][2].bindTo('position', agentMarkers[markerIndex][1], 'position');
}

function updateTitle() {
    $.ajax({
        url: "functions/ajax/getLivingRatio.php",
        context: self,
        type: "post",
        success: function(data, textstatus, jqxhr) {
            $("span#titleSpan").html(data);
        }
    });
}

function getAgentPositions() {
    $.ajax({
        url: "functions/ajax/getAgentLocs.php",
        context: self,
        type: "post",
        success: function(data, textstatus, jqxhr) {
            var locarray = jQuery.parseJSON(data);

            var tempDeathCount = 0;
            if (agentMarkers.length == locarray.length) {
                for (var i=0; i<locarray.length; i++) {
                   if (!locarray[i][3]) {
                    tempDeathCount++;
                   }
                   updateMarker(i, locarray[i]);
                }
                if (tempDeathCount != deathCount) {
                    deathCount = tempDeathCount;
                    $("span#titleSpan").html((totalEnemies-deathCount) + " of " + totalEnemies)
                }
            } else {
                // first remove the current markers
                for (var i=0; i<agentMarkers.length; i++) {
                    agentMarkers[i][1].setMap(null);
                    agentMarkers[i][2].setMap(null);
                }
                
                agentMarkers = [];

                // now add the new ones
                for (var i=0; i<locarray.length; i++) {
                    var agentloc= new google.maps.LatLng(locarray[i][0], locarray[i][1]);
                    var iconLoc = (locarray[i][3]) ? 'images/agent.png' : 'images/dead.png';
                    var agentmarker = new google.maps.Marker({position: agentloc, 
                                                              icon: iconLoc,
                                                              title: 'billy'});
                    agentmarker.setMap(map)
                    
                    var label = new Label({
                           map: map,
                           name: locarray[i][2].split(" ")[0]
                         });
                    label.bindTo('position', agentmarker, 'position');

                    agentMarkers.push(new Array(locarray[i][2], agentmarker, label));
        
                }
            }
        }
    });
}

var c=0;
function timedCount()
{
    getPhonePosition();
    getAgentPositions();
    var timeText = " " + c + " s";
    var minutes = Math.floor(c/60);
    if (minutes > 0) {
        timeText = " " + minutes + "m " + (c - minutes*60) + "s";
    }
    $('#time').text(timeText);
    c=c+2;
    t=setTimeout("timedCount()",2000);
}

function startGame() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( 

        function (position) {  
            $.ajax({
                url: "functions/ajax/startGame.php",
                context: self,
                type: "post",
                data: {
                        playerX: position.coords.longitude,
                        playerY: position.coords.latitude,
                        numAgents: $("#numAgentsVal").val(),
                        numVars: $("#numVarsVal").val(),
                      },
                success: function(data, textstatus, jqxhr) {
                    $.ajax({
                        url: "functions/ajax/getTotalEnemies.php",
                        context: self,
                        type: "post",
                        data: {
                              },
                        success: function(data, textstatus, jqxhr) {
                            totalEnemies = data;
                            $("span#titleSpan").html((totalEnemies) + " of " + totalEnemies)
                        }
                        });
                         }
            });
        }, 
        
        // next function is the error callback
        function (error) {
            switch(error.code) {
                case error.TIMEOUT:
                    break;
                case error.POSITION_UNAVAILABLE:
                    break;
                case error.PERMISSION_DENIED:
                    break;
                case error.UNKNOWN_ERROR:
                    break;
            }
        }
        );
    }
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
      return this * Math.PI / 180;
    }
}

function distance(lat1, lon1, lat2, lon2) {
    var R = 3958.75 * 1609.344; // m
    var dLat = (lat2-lat1).toRad();
    var dLon = (lon2-lon1).toRad();
    var lat1 = lat1.toRad();
    var lat2 = lat2.toRad();

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    return R * c;
}

function findAgentsInRange() {
    var nearbyAgents = new Array();
    for (var i=0; i<agentMarkers.length; i++) {
        if (agentMarkers[i][1].getIcon() == 'images/agent.png') {
            var dist = distance(marker.position.lat(),marker.position.lng(),
                            agentMarkers[i][1].position.lat(), agentMarkers[i][1].position.lng());
            if (dist < range) {
                nearbyAgents.push(agentMarkers[i][0]);
            }
        }
    }
    return nearbyAgents;
}

function showConvoDialog() {
    var agents = findAgentsInRange();

    $.mobile.changePage('startConvoDialog.php', {
        type: "post", 
        data: {
            agents: JSON.stringify(agents)
        } 
    });
}

var t;
var range;
if (!t) {
    startGame();
    range = $("input#talkRadiusVal").val();
    
    $('#main').live( 'pageinit',function(event){
        mapInit();
        updateTitle();
        t = setTimeout("timedCount()",2000);

        // Putting this on all anchors might be dangerous.
        $("a#infoButton").click(function() {
            clearTimeout(t);
        })
        $("a#convoButton").click(function() {
            clearTimeout(t);
            showConvoDialog();
        })
        $("a#problemButton").click(function() {
            reattachMap();
        });
    });
}
